package com.open4cn.simulator.connect.tcp.handler;

import com.open4cn.simulator.core.connector.ConnectAddress;
import com.open4cn.simulator.core.connector.IConnector;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.EventLoop;

import java.util.concurrent.TimeUnit;

/**
 * @author yinxiaopeng
 * @version 1.0.0
 * @company 致景科技
 * @department 飞梭BU/研发
 * @description 断开重连
 * @Email yinxiaopeng@zj.tech
 * @date 2022-05-06 14:12
 */
@ChannelHandler.Sharable
public class ReconnectHandler extends ChannelInboundHandlerAdapter {

    private IConnector connector;

    private ConnectAddress address;

    public ReconnectHandler(IConnector connector, ConnectAddress address) {
        this.connector = connector;
        this.address = address;
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        EventLoop eventLoop = ctx.channel().eventLoop();
        eventLoop.schedule(new Runnable() {
            @Override
            public void run() {
                connector.connect(address);
            }
        }, 1L, TimeUnit.SECONDS);
        super.channelInactive(ctx);
    }
}
